/**
 * Created by kevin on 2017/6/23.
 */
var express = require('express');
var router = express.Router();
var db = require('../db');
var Users = require('../models/Users');
var Roles = require('../models/Roles');
var website = require('../utils/website');

/* GET home page. */
router.all('/*',function (req,res,next) {
    if (website.url()) {
        return res.redirect('/');
    }
    next();
});

router.post('/',function (req,res) {
    // 网站信息保存
    var url = req.body['url'];
    if (!url) {
        return res.json({
            code : -1,
            message : '请填写网站地址',
            data : null
        });
    }
    var urlComs = url.split('.');
    if (!(url.indexOf('http://') < 0 || url.indexOf('https://') < 0) || urlComs.length <= 0) {
        return res.json({
            code : -1,
            message : '请填写正确的网站地址',
            data : null
        });
    }

    // 数据库
    var dbport = req.body['dbport'] || '27017';
    var database = req.body['dbname'] || 'iPack';
    var username = req.body['dbuname'] || '';
    var host = req.body['dbhost'] || 'localhost';
    var passwd = req.body['dbupwd'] || '';

    var adminPwd = req.body['pwd'];
    var adminName = req.body['username'];
    if (!adminName || !adminPwd) {
        return res.json({
            code : -1,
            message : '请填写管理员信息',
            data : null
        });
    }
    var port = req.body['port'];
    var fullUrl = url;
    if (port) {
        fullUrl = url + ':' + port;
    }
    var u = urlComs[urlComs.length - 2];
    console.log(u);

    var t = u.split('//');
    var hostPart = t[t.length - 1]+urlComs[urlComs.length - 1];
    var info = {
        install : true,
        url : fullUrl,
        name : "iPack",
        email : hostPart
        };
    website.update(info,(err) => {
        if (err) throw err;
    });

    // 数据库信息保存

    db.config(host,dbport,database,username,passwd,function (err) {
        if (err) {
            res.json({
                code : -1,
                message : err.message || err.err,
                data : null
            });
        } else {

        }
    });
});

router.get('/', function(req, res, next) {
    res.render('install/index',{title:'欢迎使用iPack'});
});

module.exports = router;
